package com.guigu.handler;

import com.guigu.exception.SsmException;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义异常处理解析器
 * 统一异常处理
 */
//@Component
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();

        if (!ObjectUtils.isEmpty(ex)) {
            if (ex instanceof SsmException) {
                SsmException ssmException = (SsmException) ex;

                // 设置了request范围的属性
                modelAndView.addObject("errorMessage", ssmException.getMessage());
                modelAndView.setViewName("error");
            }
        }
        return modelAndView;
    }
}
